/*
 * @Description:user的server层
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-11-18 17:51:50
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-10 15:05:35
 */
const execSQL = require('../db/connect')
const result = require('../utils/result')
const { guid } = require('../utils/index')
const moment = require('moment')
const { handleTokenData, getJWTPayload } = require('../config/key')
/**
 * @description: 处理注册人信息
 * @param {userName,passWord}
 * @return {Boolean}
 * @author: kafei
 */

function createInsertSql(targetTable, data) {
  const sql = `INSERT INTO ${targetTable} `
  const keys = Object.keys(data)
  let keysStr = ''
  let valueStr = ''
  for (let i = 0; i < keys.length; i++) {
    const targer = keys[i]
    const spilt = `${i === keys.length - 1 ? '' : ','}`
    keysStr += `${targer}${spilt}`
    valueStr += `'${data[targer]}'${spilt}`
  }
  const resultSql = `${sql}(${keysStr}) VALUES (${valueStr})`
  return resultSql
}
// 更新语句
function updateSql(targetTable, data, target = 'id') {
  let str = ''
  const keys = Object.keys(data)
  for (let i = 0; i < keys.length; i++) {
    const targetKey = keys[i]
    if (targetKey !== target) {
      str += `${targetKey}= '${data[targetKey] ? data[targetKey] : ''}',`
    }
  }
  const resultStr = str.substring(0, str.length - 1)
  const sql = `UPDATE ${targetTable} SET ${resultStr} WHERE ${target} = '${data[target]}';`
  return sql
}

async function create(res) {
  // const { userName, passWord } = res
  const uId = guid()
  const createTime = moment().format('YYYY-MM-DD h:mm')
  const target = Object.assign({}, res, { userId: uId, createTime, passWord: '123456' })
  const sql = createInsertSql('dy_user', target)
  await execSQL(sql)
  return Object.assign({}, res, { uId })
}

async function delUserServer(id) {
  console.log(id, 'id')
  const sql = `DELETE FROM dy_user WHERE id=${id};`
  const targetSql = `select * from dy_user WHERE id=${id};`
  const targetData = await execSQL(targetSql)
  console.log(targetData, 'targetData')
  await handleUpdateRole(targetData[0])
  const result = await execSQL(sql)
  // result
  return result
}

async function upDateUserServer(res) {
  const sql = updateSql('dy_user', res)
  handleUpdateRole(res)
  const result = await execSQL(sql)
  return result
}
async function handleUpdateRole(data) {
  const sTargetTable = 'dy_role'
  const roleSql = `select * from ${sTargetTable}`
  const roleSqlResult = await execSQL(roleSql)
  for (let i = 0; i < roleSqlResult.length; i++) {
    const userId = roleSqlResult[i].userId ? roleSqlResult[i].userId.split(',') : []
    const targetJoin = userId.filter(v => `${v}` !== `${data.userId}`).join(',')
    const sql = updateSql(sTargetTable, { userId: targetJoin, id: roleSqlResult[i].id })
    await execSQL(sql)
  }
  const targetRoleId = roleSqlResult.find(v => `${v.rid}` === `${data.rid}`)
  if (targetRoleId) {
    const targetUserId = targetRoleId.userId ? targetRoleId.userId.split(',') : []
    if (!targetUserId.includes(data.userId)) {
      targetUserId.push(data.userId)
    }
    const sql = updateSql(sTargetTable, { userId: targetUserId.join(','), id: targetRoleId.id })
    await execSQL(sql)
  }
}

async function getAllUserServer(res) {
  const sql = `select * from dy_user`
  const data = await execSQL(sql)
  return data
}

async function registerInfoServer(res) {
  const { userName } = res
  const sql = `select * from dy_user where userName='${userName}'`
  const data = await execSQL(sql)
  if (data && data.length > 0) {
    const resultUserName = data[0].userName
    if (resultUserName === userName) {
      return result('1', '该用户已存在!')
    } else {
      const resultData = await create(res)
      handleUpdateRole({ rid: resultData.rid, userId: resultData.uId })
      return result('0', { data: resultData, message: '创建成功!' })
    }
  } else {
    const resultData = await create(res)
    handleUpdateRole({ rid: resultData.rid, userId: resultData.uId })
    return result('0', { data: resultData, message: '创建成功!' })
  }
}
async function loginServer({ userName, passWord }) {
  const sql = `select * from dy_user where userName='${userName}'`
  const data = await execSQL(sql)
  console.log(data[0], 'data[0]')
  if (data && data.length > 0) {
    const resultUserName = data[0].userName
    const resultPassWord = data[0].passWord
    if (resultUserName === userName) {
      if (resultPassWord === passWord) {
        const tokenData = handleTokenData(data[0])
        return result('0', { data: tokenData, message: '登录成功!' })
      } else {
        return result('1', '密码错误!')
      }
    }
  } else {
    return result('1', '用户尚未注册!')
  }
}

async function getUserInfoServer(token) {
  const data = getJWTPayload(token)
  const { rid } = data
  const sql = `select * from dy_role where rid='${rid}'`
  const sData = await execSQL(sql)
  return sData && sData.length > 0
    ? Object.assign(data, sData[0])
    : Object.assign(data, { rid: '', rName: '', rdesc: '' })
}

module.exports = {
  registerInfoServer,
  loginServer,
  getUserInfoServer,
  upDateUserServer,
  delUserServer,
  getAllUserServer
}
